package com.cskaoyan.order.service.remote;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.commons.exception.ProcessException;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.mall.order.dto.PayOrderSuccessRequest;
import com.cskaoyan.mall.order.dto.PayOrderSuccessResponse;
import com.cskaoyan.mall.order.service.PayOrderService;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: 牟治宇
 * @description 扣减库存实现和更新订单状态
 * @date: 2022/8/3 16:13
 */
@Slf4j
@Transactional
@RestController
public class PayOrderServiceImpl implements PayOrderService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    StockMapper stockMapper;

    @RequestMapping(value = "/rpc/pay/success", method = RequestMethod.PUT)
    @Override
    public PayOrderSuccessResponse payOrderSuccess(PayOrderSuccessRequest request) {
        PayOrderSuccessResponse response = new PayOrderSuccessResponse();
        // try {
        //     request.requestCheck();
        //     String orderId = request.getOrderId();
        //
        //     //修改订单状态
        //     Order order = orderMapper.selectByPrimaryKey(orderId);
        //     order.setStatus(OrderConstants.ORDER_STATUS_PAYED);
        //     int effectRows = orderMapper.updateByPrimaryKeySelective(order);
        //     if (effectRows != 1) {
        //         log.error("更新数据库订单状态失败！");
        //         throw new ProcessException(SysRetCodeConstants.DB_EXCEPTION.getCode(), SysRetCodeConstants.DB_EXCEPTION.getMessage());
        //     }
        //
        //     //修改订单库存 根据条目购买的数量去扣减对应的商品库存
        //
        //     boolean reduceStock = reduceStockCountByOrderId(orderId);
        //     if(!reduceStock){
        //         log.error("更新锁定库存失败！");
        //         throw new BizException("更新锁定库存失败！");
        //     }
        //     //
        //     // List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);
        //     // for (OrderItem orderItem : orderItems) {
        //         // Integer num = orderItem.getNum(); //数量
        //         // Long itemId = orderItem.getItemId(); //id
        //         // Stock oldStock = stockMapper.selectStock(itemId);
        //         // Integer oldLockStock = oldStock.getLockCount(); //查询总数
        //         // // Stock stock = new Stock();
        //         // oldStock.setItemId(itemId);
        //         // int lockCount = oldLockStock - num; //扣减库存
        //         // if (lockCount < 0) {
        //         //     throw new ProcessException(SysRetCodeConstants.DB_EXCEPTION.getCode(), SysRetCodeConstants.DB_EXCEPTION.getMessage());
        //         // }
        //         // oldStock.setLockCount(lockCount);
        //         // int effectRows1 = stockMapper.updateByPrimaryKey(oldStock);
        //         // Long itemId = orderItem.getItemId();
        //         // Integer productNum = orderItem.getNum();
        //         // Stock stock = new Stock();
        //         // stock.setItemId(itemId);
        //         // stock.setLockCount(-productNum);
        //         // stock.setStockCount(0L);
        //         // stockMapper.updateStock(stock);
        //         // if (effectRows1 != 1) {
        //         //     throw new ProcessException(SysRetCodeConstants.DB_EXCEPTION.getCode(), SysRetCodeConstants.DB_EXCEPTION.getMessage());
        //         // }
        //         // Example example = new Example(OrderItem.class);
        //         // example.createCriteria().andEqualTo("orderId", orderId).andEqualTo("itemId", itemId);
        //         // OrderItem orderItem1 = new OrderItem();
        //         // orderItem1.setStatus(OrderConstants.ORDER_ITEM_STOCK_STATUS_SUCCESS); //修改订单状态
        //         //
        //         // int effectRow = orderItemMapper.updateByExampleSelective(orderItem1, example);
        //         // if (effectRow != 1) {
        //         //
        //         //     throw new ProcessException(SysRetCodeConstants.DB_EXCEPTION.getCode(),SysRetCodeConstants.DB_EXCEPTION.getMessage());
        //         // }
        //         response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        //         response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        //     }
        // } catch (ProcessException e) {
        //     ExceptionProcessorUtils.wrapperHandlerException(response,e);
        // }
        // return response;
        try {
            request.requestCheck();

            // 更新订单状态为ORDER_STATUS_PAYED=1
            String orderId = request.getOrderId();
            Order order = new Order();
            order.setOrderId(orderId);
            order.setStatus(OrderConstants.ORDER_STATUS_PAYED);
            order.setUpdateTime(new Date());
            int affectedRows = orderMapper.updateByPrimaryKeySelective(order);
            if(affectedRows != 1){
                log.error("更新数据库订单状态失败！");
                throw new BizException("更新数据库订单状态失败！");
            }

            // 更新订单锁定库存
            boolean reduceStock = reduceStockCountByOrderId(orderId);
            if(!reduceStock){
                log.error("更新锁定库存失败！");
                throw new BizException("更新锁定库存失败！");
            }
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());
        }catch (Exception e){
            log.error("PayOrderServiceImpl.payOrderSuccess Occur Exception :" + e);
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }

    private boolean reduceStockCountByOrderId(String orderId) {

        try {
            // 查询订单商品详细信息
            List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);

            // 获取订单商品Id
            List<Long> productIds = orderItems.stream().map(u -> u.getItemId()).sorted().collect(Collectors.toList());

            // 按照商品ID查询库存并锁定库存
            List<Stock> stockList = stockMapper.findStocksForUpdate(productIds);

            // 遍历订单商品，释放锁定库存
            for (OrderItem orderItem : orderItems) {
                Long productId = orderItem.getItemId();
                Integer productNum = orderItem.getNum();
                Stock stock = new Stock();
                stock.setItemId(productId);
                stock.setLockCount(-productNum);
                stock.setStockCount(0L);
                stockMapper.updateStock(stock);
            }
            return true;
        }catch (Exception e){
            log.error("OrderCoreServiceImpl.releaseLockCountByOrderId Occur Exception :" + e);
            e.printStackTrace();
            return false;
        }
    }
}
